package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.AppUserThreadLocalUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.BooleanQuery;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * app端文章关键字查询
     *
     * @param dto
     * @return
     */
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1、参数校验
        if (dto == null || StringUtils.isEmpty(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2、查询ES
        //2.1、准备SearchRequest请求
        SearchRequest searchRequest = new SearchRequest(ArticleConstants.ES_INDEX);
        //2.2、准备BooleanQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //2.3、关键字分词后查询 参与算分
        boolQueryBuilder.must(QueryBuilders.multiMatchQuery(dto.getSearchWords(), "title", "content"));
        //2.4、查询小于mindate的数据 不参与算分
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        searchRequest.source().query(boolQueryBuilder);
        //2.5、准备分页参数
        searchRequest.source().from(0);
        searchRequest.source().size(dto.getPageSize());
        //2.6、准备排序条件
        searchRequest.source().sort("publishTime", SortOrder.DESC);
        //2.7、设置高亮条件
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //2.7.1、设置高亮字段
        highlightBuilder.field("title");
        //2.7.2、设置高亮位置标签 这是和前端约定好的
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        searchRequest.source().highlighter(highlightBuilder);
        //2.8、发送请求到ES
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //3、解析ES返回的结果数据
        SearchHit[] hits = searchResponse.getHits().getHits();
        //3.0、封装最终数据
        List<Map> list = new ArrayList<>();
        //3.1、遍历
        for (SearchHit hit : hits) {
            //3.2、得到json字符串
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //3.3、处理高亮
            if (hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0) {
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                //字符串数组转字符串
                String title = StringUtils.join(titles);//由于这只有一个，所以不用加 ","
                //高亮标题
                map.put("h_title", title);
            } else {
                map.put("h_title", map.get("title"));
            }
            //将数据添加到list集合
            list.add(map);
        }
        //6、异步调用，保存搜索结果
        //6.1、先在threadLocal中得到userId
        Integer userId = AppUserThreadLocalUnit.get();
        //6.2、判断 并且保证是首页才保存，不然同一次仅仅是时间不同并且时间还很短
        if (userId != null && dto.getFromIndex() == 0) {
            apUserSearchService.insert(dto.getSearchWords(),userId);
        }
        //5、返回结果
        return ResponseResult.okResult(list);
    }

}
